const fs = require('fs');
const url = require('url');
const http = require('http');
const path = require('path');

// const root = path.join(__dirname, 'public');
const root = path.join(path.resolve(), 'public');

// 创建服务器
const sever = http.createServer(function (request, response) {
  let pathname = url.parse(request.url).pathname;
  // pathname = pathname === '/' ? 'index.html' : pathname;
  let filepath = path.join(root, pathname);

  fs.stat(filepath, function (err, stats) {
    // 获取文件状态
    if (err || stats.isDirectory()) {
      let options = url.parse(request.url);
      options.method = request.method;
      options.headers = request.headers;
      options.hostname = '127.0.0.1';
      options.port = 9527;

      let proxyRequest = http.request(options, function (proxyResponse) {
        response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
        proxyResponse.pipe(response);
      });
      request.pipe(proxyRequest);
      // proxyRequest.end();

      // console.error(err);
      // response.writeHead(404);
      // response.end('404 Not Found');
    } else {
      response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
      fs.createReadStream(filepath).pipe(response);
    }
  });
});
sever.listen(80, '0.0.0.0');
console.info('Server is running at http://127.0.0.1:80/index.html');